<!-- @format -->

<template>
  <div class="card-container">
    <div v-for="(item, index) in params">
      <select-speakers
        :title="getMapLabel('speakerType', role) + '环节'"
        :speakerFormat="speakerFormat"
        v-model="item.speakers"
        :placeholder="`请选择${getMapLabel('speakerType', role)}`"
      >
        <template #button>
          <van-icon v-if="isAllowUpdate" @click="clickDelete" name="delete-o" />
          <!-- <div v-if="role != 1">
            <van-icon v-if="!index" name="plus" @click="clickAdd" />
            <van-icon v-else name="minus" @click="clickRemove(index)" />
          </div> -->
        </template>
      </select-speakers>

      <div v-if="role == 4">
        <select-checkbox
          title="主持环节"
          :list="hostRelationUUIDOptions"
          v-model="item.uuidList"
          empty-text="暂无讲题，请先配置讲题"
        ></select-checkbox>
      </div>
      <div v-else>
        <select-topics
          title="讲题"
          v-model="item.topic"
        ></select-topics>

        <select-time
          title="开始时间"
          v-model="item.startTime"
          @confirm="confirmStartTime($event, index)"
        ></select-time>

        <select-picker
          title="环节时长"
          ref="refSelectPicker"
          :list="meetingStepOptions"
          v-model="item.step"
          @confirm="confirmStep($event, index)"
        ></select-picker>

        <select-time
          title="结束时间"
          readonly
          v-model="item.endTime"
        ></select-time>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, toRefs, watch, computed } from 'vue'
import { showConfirmDialog } from 'vant';
import useConstant from '@/hooks/useConstant'
import { useStore } from 'vuex'
 
const refSelectPicker = ref()
const store = useStore();
const emits = defineEmits(['update', 'delete'])
const props = defineProps({
  speakerItem: {
    type: Object,
    default: () => ({})
  },
  schedulesIndex: {
    type: Number,
    default: 0
  },
  role: {
    type: String,
    default: ''
  },
  schedules: {
    type: Array,
    default: () => ([])
  },
  baseInfo: {
    type: Object,
    default: () => ({})
  },
  isAllowUpdate: {
    type: Boolean,
    default: true
  }
})
const { getMapLabel } = useConstant();

const params = ref([])

const meetingStepOptions = computed(() => JSON.parse(store.state.tenant.config.scheduleGapConfig).map(item => ({ 
  ...item,
  text: item.name
})));
const hostRelationUUIDOptions = computed(() => {
  const { schedules } = toRefs(props)
  const list = []
  const zcSpeakers = []
  schedules.value.forEach(item => {
    (item || []).forEach(val => {
      if (val.scheduleType == 4) {
        zcSpeakers.push(val)
      }
    })
  });
  const selectTopic = zcSpeakers.reduce((val, item) => [...val, ...(item.uuidList || [])], [])
  schedules.value.forEach(item => {
    (item || []).forEach(speaker => {
      speaker.topic && list.push({
        text: `${speaker.topic}（${speaker.startTime}-${speaker.endTime}）`,
        value: speaker.uuid,
        disabled: selectTopic.includes(speaker.uuid)
      })
    })
  })
  
  return list
})
const priceConfig = computed(() => {
  return store.state.tenant.config.speakerFeeConfig ? JSON.parse(store.state.tenant.config.speakerFeeConfig) : {}
})

function confirmStartTime(data, index) {
  setEndTime(index)
  refSelectPicker.value[index].clickSelectDate()
}
function confirmStep (data, index) {
  setEndTime(index)
}
function setEndTime (index) {
  if (!params.value[index].startTime || !params.value[index].step) return
  const startTime = params.value[index].startTime.split(':')
  const step = Number.parseInt(params.value[index].step)
  const minute = startTime[0] * 60 + Number.parseInt(startTime[1]) + step;
  const endTimeM = Math.floor(minute / 60);
  const endTimeS = minute % 60;
  const endTime = [endTimeM > 9 ? endTimeM : `0${endTimeM}`, endTimeS > 9 ? endTimeS : `0${endTimeS}`]
  params.value[index].endTime = endTime.join(':');
}

function getPrevLinkStartTime () {
  const { schedules, schedulesIndex, baseInfo, speakerItem } = toRefs(props);
  
  if (!schedules.value.length) return speakerItem.value.startTime || ''
  if (params.value.length) {
    const prevSpeaker = params.value[params.value.length - 1];
    return prevSpeaker.endTime || '';
  }
  if (schedulesIndex.value) {
    const prevSchedules = schedules.value[schedulesIndex.value - 1];
    const prevSpeaker = prevSchedules[prevSchedules.length - 1];
    return prevSpeaker.endTime || '';
  }

  return '';
}
function clickDelete () {
  emits('delete')
}
function clickAdd () {
  const { speakerItem, role } = toRefs(props);
  params.value.push(JSON.parse(JSON.stringify({
    uuid: new Date().getTime(),
    ...speakerItem.value,
    startTime: getPrevLinkStartTime(),
    scheduleType: role.value
  })))
}

function clickRemove (index) {
  showConfirmDialog({
    title: '温馨提示',
    message: '删除后无法恢复，确定要删除吗？',
  }).then(() => {
    params.value.splice(index, 1)
  }).catch(() => {})
}
function setRolePrice (role) {
  const roleConfig = priceConfig.value?.find(item => item.role == role)
  const defaultPrice = roleConfig?.fee.find(item => item.isDefault)
  return {
    speakerAppearanceFeeAftertax: defaultPrice?.aftertax || 0,
    speakerAppearanceFeePretax: defaultPrice?.pretax || 0,
  }
}
function speakerFormat(list) {
  const { role } = toRefs(props);
  return list.map((item) => ({
    speakerId: item.id || item.speakerId,
    ...setRolePrice(role.value),
    speakerName: item.name || item.speakerName,
    speakerRole: role.value
  }))
}

watch(
  () => params.value,
  (newVal) => emits('update', newVal),
  { deep: true }
)
onMounted(() => {
  clickAdd();
})

defineExpose({
  params,
  setParams (list = []) {
    params.value = list
    emits('update', list)
  }
})
</script>
